const express = require('express')
const router = express.Router()
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const sqlGetData = require('../db')
const { auth } = require('../utils')


// 注册
router.post('/register', async (req, res) => {
    const { userName, passWord, auth } = req.body
    // 判断用户是否存在
    let data = await sqlGetData(`select * from user where name='${userName}'`)

    if (data.length > 0) {
        res.send({
            code: -1,
            msg: "该账号已存在"
        })
    } else {
        // 加密
        const md5 = crypto.createHash('md5')
        const hash = md5.update(passWord).digest('hex')
        await sqlGetData(`insert into user (name, password, userId) values ('${userName}', '${hash}', ${auth})`)
        // 插入数据库
        res.send({
            code: 1,
            data: '注册成功'
        })
    }
})

// 登录
router.post('/login', async (req, res) => {
    const { userName, passWord } = req.body
    // 判断用户是否存在
    // 加密
    const md5 = crypto.createHash('md5')
    const hash = md5.update(passWord).digest('hex')
    let data = await sqlGetData(`select * from user where name='${userName}' and password='${hash}'`)
    let userId = data[0].userId
    if (data.length > 0) {
        let token = jwt.sign({
            userId,
            passWord,
            userName
        }, 'key', {
            expiresIn: '1h'
        })
        res.send({
            code: 1,
            msg: '登录成功',
            token
        })
    } else {
        // 账号密码不匹配
        res.send({
            code: -1,
            msg: '账号密码不匹配'
        })
    }
})

// 获取用户信息
router.get('/getUserInfo', auth, (req, res) => {
    // 通过token 解析出用户id
    const token = req.headers.authorization
    jwt.verify(token, 'key', async (err, datas) => {
        // data.userName  用户名称
        let data = await sqlGetData(`select * from userinfo where name='${datas.userName}'`)
        console.log(data)
        res.send({
            code: 1,
            msg: "获取用户信息成功",
            data
        })
    })
})

module.exports = router